package libs
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.net.navigateToURL;
	
	import mx.controls.Alert;
	import mx.controls.ToolTip;
	import mx.controls.dataGridClasses.DataGridColumn;
	import mx.core.Application;
	import mx.effects.Fade;
	import mx.effects.Move;
	import mx.effects.Parallel;
	import mx.effects.easing.Elastic;
	import mx.events.ValidationResultEvent;
	import mx.formatters.DateFormatter;
	import mx.managers.PopUpManager;
	import mx.managers.ToolTipManager;
	import mx.utils.ArrayUtil;
	import mx.utils.ObjectUtil;
	
	public class Utils
	{	import mx.validators.Validator;
		import mx.collections.ArrayCollection;
		import mx.rpc.xml.SimpleXMLEncoder;
		import mx.rpc.xml.SimpleXMLDecoder;
		import mx.core.IFlexDisplayObject;
		import flash.xml.*;
		
		private var alertCreationCompleteEffect:Parallel;
		private var myTip:ToolTip;
		
		public function genUtils():void
		{
		var fader:Fade = new Fade();
        fader.duration = 500;

        var mover:Move = new Move();
        mover.yFrom = 0;
        mover.easingFunction = Elastic.easeOut;
        mover.duration = 1000;
        
        alertCreationCompleteEffect = new Parallel();
        alertCreationCompleteEffect.addChild(fader);
        alertCreationCompleteEffect.addChild(mover);
        
		}		
		
		public function dateLabelFunction(item:Object,column:DataGridColumn):String{
                var val:Number;
                var formatter:DateFormatter = new DateFormatter();
                
                formatter.formatString = "DD/MM/YYYY"

                val = item[column.dataField];
                
                return formatter.format(val);                            	
        }
		
		public function numLabelFunction(item:Object,column:DataGridColumn):String{
                var val:Number;
                var formatter:DateFormatter = new DateFormatter();
                
                formatter.formatString = "DD/MM/YYYY"

                val = item[column.dataField];
                
                return formatter.format(val);                            	
        }
        	    
	    public function createBigTip(text:String,width:Number,height:Number):void {
	        myTip = ToolTipManager.createToolTip(text,10,20) as ToolTip;
	        myTip.setStyle("backgroundColor",0xFFCC00);
	        myTip.width = width;
	        myTip.height = height;
	    }

	    public function destroyBigTip():void {
	        ToolTipManager.destroyToolTip(myTip);
	    }

		public function objectToXML(obj:Object):XML 
        {
            var qName:QName = new QName("root");
            var xmlDocument:XMLDocument = new XMLDocument();
            var simpleXMLEncoder:SimpleXMLEncoder = new SimpleXMLEncoder(xmlDocument);
            var xmlNode:XMLNode = simpleXMLEncoder.encodeValue(obj, qName, xmlDocument);
            var xml:XML = new XML(xmlDocument.toString());

            return xml;
        }
        public function convertXmlToArrayCollection( xmlString:String ):ArrayCollection
		{
		    var xml:XMLDocument = new XMLDocument( xmlString );
		 
		    var decoder:SimpleXMLDecoder = new SimpleXMLDecoder();
		    var data:Object = decoder.decodeXML( xml );
		    var array:Array = ArrayUtil.toArray( data.rows.row );
		 
		    return new ArrayCollection( array );
		}
		public function validate(validator:Validator):Boolean{                
        	// Get a reference to the component that is the
            // source of the validator.
            var validatorSource:DisplayObject = validator.source as DisplayObject;               
            // Suppress events if the current control being validated is not
            // the currently focussed control on the form. This stops the user
            // from receiving visual validation cues on other form controls.
            var suppressEvents:Boolean = false;//(validatorSource != focussedFormControl);                
            // Carry out validation. Returns a ValidationResultEvent.
            // Passing null for the first parameter makes the validator 
            // use the property defined in the property tag of the
            // <mx:Validator> tag.
            var event:ValidationResultEvent = validator.validate(null, suppressEvents);                                 
            // Check if validation passed and return a boolean value accordingly.
            var currentControlIsValid:Boolean = (event.type == ValidationResultEvent.VALID);                 
            // Update the formIsValid flag
            //tab2IsValid = tab2IsValid && currentControlIsValid;                 
            return currentControlIsValid;
		}
		
        public function getDefaultIndex(arr:ArrayCollection,matchPath:String=""):int{
			//posiciona el arrayCollection en el index que encuentre como default (si lo tuviera) y lo retorna.
			var index:int;
							
			for (var i:int=0;i < arr.length;i++){
				if (arr.getItemAt(i).sn_default ==-1){
					index = i;
				}
			}
			return index;
		}
		
		public function getIndexAt(arr:ArrayCollection,matchPath:String=""):int{
			//posiciona el arrayCollection en el index que encuentre .
			var index:int;
							
			for (var i:int=0;i < arr.length;i++){
				if (arr.getItemAt(i).codigo == matchPath){
					index = i;
				}
			}
			return index;
		}
		
		public function MostrarWindow(win:IFlexDisplayObject):void{
          	var escena:Sprite = Sprite(Application.application);
            
      		PopUpManager.addPopUp(win, escena, true);
      		PopUpManager.centerPopUp(win);
        }
        
        public function showAlert(error:String,smallIcon:Class,bigIcon:Class,msgType:String):void{
            	var alert:Alert = Alert.show(error, msgType,4,null,null,bigIcon);
                alert.setStyle("creationCompleteEffect", alertCreationCompleteEffect);
                alert.titleIcon = smallIcon;
                alert.isPopUp = false;
                alert.cacheAsBitmap = true;
        }
        
        public function navigateURL(url:String,vars:URLVariables=null):void{
        	var urlRequest:URLRequest = new URLRequest(url);
        	urlRequest.method = URLRequestMethod.GET;
			urlRequest.data = vars;
			
			navigateToURL(urlRequest);
        }
        /* public function resetAutoLogOut(closeFunction:Function,activityTimeoutId:uint):uint{
				// Clear old timeout.
				clearTimeout(activityTimeoutId);
				
				// Set up a timeout to trigger the log out function
				// after 10 seconds.
				var delay:Number = 10 * 1000;
				return setTimeout(closeFunction, delay);
		} */
		
        public function setErrorTip(msg:String,errorTip:ToolTip, control:Object=null):void{
        	            	            	            	
            if (msg==""){
            	if(errorTip){
            		ToolTipManager.destroyToolTip(errorTip);
            	}
            }else{
            	errorTip = ToolTipManager.createToolTip(msg,control.x + control.width, control.y) as ToolTip;
            	errorTip.setStyle("styleName", "errorTip");
            }
		}
		public function validateCBU(CBU:String):Boolean{
				/**
				 * Formato del CBU:
					 EEESSSS-V TTTTTTTTTTTTT-V
					 Bloque 1 (total 8 posiciones):
					 EEE - Número de entidad (3 posiciones)
					 SSSS - Número de sucursal (4 posiciones)
					 V - Dígito verificador de las primeras 7 posiciones
					 Bloque 2 (total 14 posiciones):
					 TTTTTTTTTTTTT - Identificación de la cuenta individual
					 V - Dígito verificador de las anteriores 13 posiciones
					
					 Para el cálculo de los dígitos verificadores se
					 debe aplicar la clave 10 con el ponderador 9713
					 * 
				**/
				var bloque1:String;
				var bloque2:String;
								
				if (CBU.length == 22){
					bloque1 = CBU.substr(0,8);
					bloque2 = CBU.substr(8,14);
					return validateDigitoCbu(bloque1) && validateDigitoCbu(bloque2);
				}else{
					return false;
				}
		}
		
		private function validateDigitoCbu(bloque:String):Boolean{
			
			var suma:Number = 0;
			var largoBloque:Number;
			var digito:String;
			var digitoResul:String;
			var bloqueSinDig:String;
			var arrBloque:Array;
			const POND:String = "9713";
			
			largoBloque = bloque.length;
			digito = bloque.substr(largoBloque-1,1);
			bloqueSinDig = bloque.substr(0,largoBloque-1);
												
 			if (largoBloque ==8){//primer bloque
					suma = 	(7 * (Number(bloqueSinDig.substr(0,1)) + Number(bloqueSinDig.substr(4,1)))) +
							(1 * (Number(bloqueSinDig.substr(1,1)) + Number(bloqueSinDig.substr(5,1)))) +
							(3 * (Number(bloqueSinDig.substr(2,1)) + Number(bloqueSinDig.substr(6,1)))) +
							(9 * (Number(bloqueSinDig.substr(3,1)))); 
		
			}else{//segundo bloque
 					suma = 	(7 * (Number(bloqueSinDig.substr(2,1)) + Number(bloqueSinDig.substr(6,1)) + Number(bloqueSinDig.substr(10,1)))) +
							(1 * (Number(bloqueSinDig.substr(3,1)) + Number(bloqueSinDig.substr(7,1)) + Number(bloqueSinDig.substr(11,1)))) +
							(3 * (Number(bloqueSinDig.substr(0,1)) + Number(bloqueSinDig.substr(4,1)) + Number(bloqueSinDig.substr(8,1)) + Number(bloqueSinDig.substr(12,1)))) +
							(9 * (Number(bloqueSinDig.substr(1,1)) + Number(bloqueSinDig.substr(5,1)) + Number(bloqueSinDig.substr(9,1)))); 							
			} 
			
			digitoResul = ObjectUtil.toString(10-(suma%10));
			return (digito == digitoResul.substr(digitoResul.length-1,1));
				
		}
				
		public function validateCUIT(CUIT:String):Boolean{
 				if (CUIT.length == 11){								
					var XA:Number = new Number(CUIT.substr(0, 1)) * 5;
					var XB:Number = new Number(CUIT.substr(1, 1)) * 4;
					var XC:Number = new Number(CUIT.substr(2, 1)) * 3;
					var XD:Number = new Number(CUIT.substr(3, 1)) * 2;
					var XE:Number = new Number(CUIT.substr(4, 1)) * 7;
					var XF:Number = new Number(CUIT.substr(5, 1)) * 6;
					var XG:Number = new Number(CUIT.substr(6, 1)) * 5;
					var XH:Number = new Number(CUIT.substr(7, 1)) * 4;
					var XI:Number = new Number(CUIT.substr(8, 1)) * 3;
					var XJ:Number = new Number(CUIT.substr(9, 1)) * 2;
					//Suma los resultantes.
					var x:Number = XA + XB + XC + XD + XE + XF + XG + XH + XI + XJ;
					//Calcula el dígito de control.
					var control:Number = (11-(x % 11)) % 11;
					//Verifica si el dígito de control ingresado difiere con el calculado.
					if(control != Number(CUIT.substr(10, 1))){
						return false;						
					}
					
 				}else{
					return false;
				}
				return true;
		}                		
	}
	
	
	
}